package com.vchello.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.vchello.bean.user.User;
import com.vchello.contants.CONTANTS;

/**
 * 
 * @author power
 *
 */
public class MyFilter implements Filter{
	
	public void destroy() {
	}

	/**
    * 替换原始的Request，修改为
    * com.etnetchina.servlet.wrapper.CacheSessionHttpServletReqeust。
    * 并根据是否新生成了Session来更新客户端的cookie.
    * 
    * @param request 请求。
    * @param response 响应。
    * @param chain 下一个过滤器。
    * @throws java.io.IOException
    * @throws javax.servlet.ServletException
    */
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		RequestDispatcher dispatcher = arg0.getRequestDispatcher("/admin/login");//这里设置如果没有登陆将要转发到的页面  
		HttpServletRequest req = (HttpServletRequest) arg0;  
		HttpServletResponse res =  (HttpServletResponse) arg1;  
		HttpSession session = req.getSession();
		
		String path = req.getServletPath();
		
		
		if(path != null && path.contains("/admin/") && !path.contains("/admin/login")){
			User user = (User) session.getAttribute("user");
			if(null == user) {
				dispatcher.forward(arg0, arg1);
			}else if(user.getType() == CONTANTS.ROLEIDS[3]){
				arg2.doFilter(arg0, arg1); 
			}else{
				dispatcher.forward(arg0, arg1);
			}
		} else {
			arg2.doFilter(arg0, arg1);
		}
		
	}
	
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}

}
